﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CMPPProtocol
{
    /// <summary>
    /// 编码帮助类。
    /// </summary>
    internal static class Convert
    {

        /// <summary>
        /// 字节流解码。
        /// </summary>
        public static string ToString(byte[] buffer, int startIndex, int length, CMPPEncoding coding)
        {
            string result = "";
            int strlength = 0;
            for (int i = startIndex; i < buffer.Length; i++)
            {
                if (buffer[i] == 0)
                {
                    break;
                }
                else
                {
                    strlength++;
                }
                if (strlength >= length)
                {
                    break;
                }
            }
            switch (coding)
            {
                case CMPPEncoding.CODING_GBK:
                    result = System.Text.UnicodeEncoding.GetEncoding("gb2312").GetString(buffer, startIndex, strlength);
                    break;
                case CMPPEncoding.CODING_ASCII:
                    result = System.Text.Encoding.ASCII.GetString(buffer, startIndex, strlength);
                    break;
                case CMPPEncoding.CODING_UCS2:
                    result = System.Text.Encoding.BigEndianUnicode.GetString(buffer, startIndex, strlength);
                    break;
            }
            return result.Replace("\0","");
        }

        /// <summary>
        /// 字节流编码。
        /// </summary>
        public static byte[] ToBytes(string value, CMPPEncoding coding)
        {
            if (value != null)
            {
                switch (coding)
                {
                    case CMPPEncoding.CODING_GBK:
                        return UnicodeEncoding.GetEncoding("gb2312").GetBytes(value);
                    case CMPPEncoding.CODING_ASCII:
                        return System.Text.Encoding.ASCII.GetBytes(value);
                    case CMPPEncoding.CODING_UCS2:
                        return System.Text.Encoding.BigEndianUnicode.GetBytes(value);
                }
            }
            return new byte[0];
        }
    }
}
